package controllers

import (
	"database/sql"
	"net/http"
	"strconv"

	"web-service/models"

	"github.com/gin-gonic/gin"
)

type BookExcerptController struct {
	DB *sql.DB
}

// CreateBookExcerpt 创建新的书摘
func (c *BookExcerptController) CreateBookExcerpt(ctx *gin.Context) {
	var excerpt models.BookExcerpt
	if err := ctx.ShouldBindJSON(&excerpt); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "请求参数错误",
			"error":   err.Error(),
		})
		return
	}

	// 从URL参数获取bookId
	bookID, err := strconv.ParseInt(ctx.Param("bookId"), 10, 64)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的书籍ID",
			"error":   err.Error(),
		})
		return
	}
	excerpt.BookID = bookID

	if err := models.CreateBookExcerpt(c.DB, &excerpt); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "创建书摘失败",
			"error":   err.Error(),
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "创建成功",
		"data":    excerpt,
	})
}

// UpdateBookExcerpt 更新书摘
func (c *BookExcerptController) UpdateBookExcerpt(ctx *gin.Context) {
	excerptID, err := strconv.ParseInt(ctx.Param("id"), 10, 64)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的书摘ID",
			"error":   err.Error(),
		})
		return
	}

	var excerpt models.BookExcerpt
	if err := ctx.ShouldBindJSON(&excerpt); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "请求参数错误",
			"error":   err.Error(),
		})
		return
	}
	excerpt.ID = excerptID

	if err := models.UpdateBookExcerpt(c.DB, &excerpt); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "更新书摘失败",
			"error":   err.Error(),
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "更新成功",
	})
}

// GetBookExcerpts 获取指定书籍的所有书摘
func (c *BookExcerptController) GetBookExcerpts(ctx *gin.Context) {
	bookID, err := strconv.ParseInt(ctx.Param("bookId"), 10, 64)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的书籍ID",
			"error":   err.Error(),
		})
		return
	}

	excerpts, err := models.GetBookExcerptsByBookID(c.DB, bookID)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "获取书摘列表失败",
			"error":   err.Error(),
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": gin.H{
			"list": excerpts,
		},
	})
}
